package com.demo209_长度最小的子数组;

/**
 * 使用滑动窗口的方式来解决
 * 定义两个指针,分别指向窗口的前端和后端
 */
public class Solution_滑动窗口 {
    public static void main(String[] args) {
        int[] ints={2,3,1,2,4,3};
        int target=7;
        int len = minSubArrayLen(target, ints);
        System.out.println(len);
    }
    public static int minSubArrayLen(int target, int[] nums) {
        //1.求数组的总和
        int sum=0;
        for (int i = 0; i < nums.length; i++) {
            sum+=nums[i];
        }
        //2.特判
        if (sum<target){
            return 0;
        }
        int min=0;
        int left=0;
        int right=0;
        int total=0;
        for (int i = 0; i < nums.length; i++) {
            total+=nums[i];
            right=i;
            while (total-nums[left]>=target){
                total=total-nums[left];
                left++;
            }
            if (total>=target){
                int len=right-left+1;
                min = min==0?len:Math.min(len,min);
            }

        }

        return min;

    }
}
